package video;

import java.io.IOException;
import java.util.Iterator;

import net.cl.tools.HttpProxy;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class Tudou {

	private static final Log log = LogFactory.getLog(Tudou.class);

	private static final String INDEX_PREFIX = "http://v2.tudou.com/v?vn=02&st=1%2C2&it=";

	public Tudou() {
	}

	public String getVideoSource(String videoKey, String userAgent) {
		String url = INDEX_PREFIX + videoKey;
		try {
			HttpProxy p = new HttpProxy(url);
			p.userAgent(userAgent);
			Document document = DocumentHelper.parseText(p.get());
			Element root = document.getRootElement();
			for (@SuppressWarnings("unchecked")
			Iterator<Element> iterator = root.nodeIterator(); iterator.hasNext();) {
				Element u = iterator.next();
				if (u != null) {
					return u.getText();
				}
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args) {
		Tudou tudou = new Tudou();
		System.out.println(tudou.getVideoSource("75629467",
				"Mozilla/5.0 (Windows NT 5.1; rv:2.0) Gecko/20100101 Firefox/4.0"));
	}

}
